package com.example.cloud.controller;

import com.example.cloud.exception.AuthException;
import com.example.cloud.interceptor.AuthInterceptor;
import com.example.cloud.util.PageRequest;
import com.example.cloud.util.PageResult;
import com.example.cloud.util.Result;
import com.example.cloud.entity.User;
import com.example.cloud.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Tag(name = "用户管理", description = "用户相关的接口")
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {
    
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    
    private final UserService userService;
    
    /**
     * 获取当前用户信息
     */
    @Operation(summary = "获取当前用户信息", description = "获取当前登录用户的详细信息")
    @GetMapping("/current")
    public Result<Map<String, Object>> getCurrentUserInfo(HttpServletRequest request) {
        try {
            // 从请求属性中获取用户ID
            Long userId = AuthInterceptor.getCurrentUserId(request);
            // 拦截器已经处理了认证，这里不需要再次检查userId是否为null
            
            logger.info("获取当前用户信息，userId: {}", userId);
            
            User user = userService.findById(userId);
            if (user == null) {
                throw new AuthException("用户不存在");
            }
            
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("nickName", user.getNickName());
            userInfo.put("avatarUrl", user.getAvatarUrl());
            userInfo.put("gender", user.getGender());
            userInfo.put("country", user.getCountry());
            userInfo.put("province", user.getProvince());
            userInfo.put("city", user.getCity());
            userInfo.put("language", user.getLanguage());
            userInfo.put("createTime", user.getCreateTime());
            
            return Result.success(userInfo);
        } catch (AuthException e) {
            throw e;
        } catch (Exception e) {
            logger.error("获取当前用户信息失败: {}", e.getMessage(), e);
            return Result.error("获取用户信息失败：" + e.getMessage());
        }
    }
} 